<template>
  <view class="app-container">
    <image class="background" src="/static/images/background.png" mode="aspectFill"></image>

    <view class="bar-box" :style="{ marginTop: titleMargin + 'px' }">
      <image class="back" src="/static/images/back.png" @click="back"></image>
      <view class="title">我的推广</view>
    </view>

    <view class="info">
      <image class="qr" @click="previewQr(info.qr_path)" :src="info.qr_path"></image>
    </view>

    <button :plain="true" class="poster-btn" @click="openPoster">生成海报</button>

    <view class="gather-box">
      <view class="text">当前收益</view>
      <view class="text">{{ info.profit }}</view>
      <view class="btn-box">
        <view class="box" @click="openRoleContentModal">
          <image class="icon" src="/static/images/search_active.png"></image>
          <view>权益查看</view>
        </view>
        <view class="box" @click="goProfitList">
          <image class="icon" src="/static/images/profit_icon.png"></image>
          <view>收益明细</view>
        </view>
        <view class="box" @click="goWithdraw">
          <image class="icon" src="/static/images/withdraw_icon.png"></image>
          <view>我要提现</view>
        </view>
      </view>
    </view>

    <view class="detail-box">
      <view>共计推广：{{ info.share_count }}</view>
      <scroll-view scroll-y enable-flex @scrolltolower="loadMore" class="list-box">
        <view class="box" v-for="(item, index) in list" :key="index" @click="goUserDetails(item.id)">
          <view class="user-info">
            <image class="avatar" mode="aspectFill" :src="item.avatar ? item.avatar : '/static/images/default_avatar.png'"></image>
            <view>
              <view class="name">ID：{{ item.id_num }}</view>
              <view class="name">昵称：{{ item.username }}</view>
              <view v-if="item.mobile" class="name">手机号：{{ item.mobile }}</view>
            </view>
          </view>
          <view class="time">{{ item.create_time_desc }}入驻</view>
        </view>
      </scroll-view>
    </view>

    <view v-if="roleContentModal" class="modal-overlay" @click="closeRoleContentModal">
      <view class="modal" @click.stop>
        <view class="modal-content">
          <image class="close" src="/static/images/close.png" @click="closeRoleContentModal"></image>
          <scroll-view scroll-y enable-flex class="content">
            <rich-text space="nbsp" :nodes="info.role_content"></rich-text>
          </scroll-view>
        </view>
      </view>
    </view>

    <!-- 海报 -->
    <view class="poster-container" v-if="showPoster">
      <canvas :canvas-id="postCanvasId" style="width: 670rpx; height: 1200rpx;"></canvas>
      <view class="poster-btn-box">
        <button class="btn close" @click="closePoster">关闭</button>
        <button class="btn" @click="savePoster">下载保存到手机相册</button>
      </view>
    </view>

  </view>
</template>

<script>
import previewImg from '@/utils/function/common'

export default {
  computed: {
    previewImg() {
      return previewImg
    }
  },
  data() {
    return {
      titleMargin: 0, // 动态顶部间距
      info: [],
      list: [],
      page: 1,
      pagesize: 10,
      roleContentModal: false,
      withdraw_type: 0,
      profit: 0,
      showPoster: false,
      postCanvasId: 'canvas'
    };
  },
  created() {
    this.setDynamicMargin(); // 设置动态间距
  },

  onLoad: function () {
    uni.hideShareMenu();

    var user_id = uni.getStorageSync('user_id')
    var scene_user_id = uni.getStorageSync('scene_user_id') ? uni.getStorageSync('scene_user_id') : 0;

    this.$http.post('/index/Api/userCenter', {user_id, scene_user_id}).then(res => {
      if (res.data.result == 1) {
        var info = res.data.data;

        // 存储认证状态
        uni.setStorageSync('rz_status', info.rz_status)
        uni.setStorageSync('avatar', info.avatar);

        this.info = info;
        this.profit = info.profit;
        this.withdraw_type = info.withdraw_type;
        if (res.data.data.up_user_id > 0) uni.removeStorageSync('scene_user_id');

        this.drawPoster(info.qr_path, info.avatar, info.username);
      } else {
        this.$common.doErrorResult(res)
      }
    })

    this.shareUserList();
  },

  methods: {
    goUserDetails: function (user_id){
      uni.navigateTo({
        url: '/pages/user_details/user_details?user_id=' + user_id
      })
    },

    setDynamicMargin() {
      const windowInfo = uni.getWindowInfo();
      this.titleMargin = windowInfo.statusBarHeight + 10; // 直接使用状态栏高度
    },

    back: function () {
      uni.navigateBack();
    },

    previewQr: function (qr) {
      this.$common.previewImg(qr)
    },

    loadMore: function () {
      this.shareUserList(this.page + 1);
    },

    shareUserList: function (incPage = 0) {
      var page = incPage ? incPage : this.page;

      uni.showLoading({
        title: '数据加载中...',
        mask: true
      })

      this.$http.post('/index/Api/shareUserList', {
        user_id: uni.getStorageSync('user_id'),
        page: page,
        pagesize: this.pagesize
      }).then((res) => {
        if (res.data.result == 1) {
          if (page == 1) {
            this.list = res.data.data;
          } else {
            // 加载更多
            var list = this.list;

            for (var i = 0; i < res.data.data.length; i++) {
              list.push(res.data.data[i]);
            }

            this.list = list;
            this.page = page;
          }

          setTimeout(() => {
            uni.hideLoading();
          }, 500)
        } else {
          uni.hideLoading();
          if (page == 1) {
            this.list = [];
          } else {
            this.$common.doErrorResult(res);
          }
        }
      })
    },

    openRoleContentModal: function () {
      this.roleContentModal = true;
    },

    closeRoleContentModal: function () {
      this.roleContentModal = false;
    },

    goProfitList: function () {
      uni.navigateTo({
        url: '/pages/profit_list/profit_list'
      })
    },

    goWithdraw: function () {
      uni.navigateTo({
        url: '/pages/withdraw/withdraw?type=' + this.withdraw_type + '&profit=' + this.profit
      })
    },

    /**
     * 设置圆角
     * */
    drawRoundedRect: function (ctx, x, y, width, height, radius) {
      ctx.beginPath();
      ctx.moveTo(x + radius, y);
      ctx.lineTo(x + width - radius, y);
      ctx.arcTo(x + width, y, x + width, y + radius, radius);
      ctx.lineTo(x + width, y + height - radius);
      ctx.arcTo(x + width, y + height, x + width - radius, y + height, radius);
      ctx.lineTo(x + radius, y + height);
      ctx.arcTo(x, y + height, x, y + height - radius, radius);
      ctx.lineTo(x, y + radius);
      ctx.arcTo(x, y, x + radius, y, radius);
      ctx.closePath();
      ctx.fill();
    },

    drawPoster: function (qr_path, avatar, username) {
      const ctx = uni.createCanvasContext(this.postCanvasId);

      // 绘制背景图片
      ctx.drawImage('/static/images/poster.png', -17, -20, 355, 610);

      uni.downloadFile({
        url: avatar, // 使用在线地址
        success: (downloadResult) => {
          if (downloadResult.statusCode === 200) {
            // 绘制头像
            // 绘制圆角头像
            const avatarPath = downloadResult.tempFilePath;

            // 设置裁切区域为圆形
            ctx.save();  // 保存当前绘制状态
            ctx.beginPath();
            ctx.arc(142 + 25, 395 + 25, 25, 0, Math.PI * 2); // 圆形裁切区域
            ctx.clip();  // 应用裁切区域

            // 绘制头像，头像大小为50x50，绘制到(142, 150)位置
            ctx.drawImage(avatarPath, 142, 395, 50, 50);
            ctx.restore();  // 恢复到之前的绘制状态
          }
        }
      });

      // 绘制白色背景区域（放小程序码）
      ctx.setFillStyle('#FFFFFF');
      this.drawRoundedRect(ctx, 112, 281, 110, 110, 10);

      // 下载小程序码
      uni.downloadFile({
        url: qr_path, // 使用在线地址
        success: (downloadResult) => {
          if (downloadResult.statusCode === 200) {
            // 绘制小程序码
            ctx.drawImage(downloadResult.tempFilePath, 117, 286, 100, 100);

            // 设置字体
            ctx.font = 'bold 18px sans-serif'; // 设置为加粗
            // 获取文本内容
            const text = username + ' 邀请您';
            // 绘制居中显示的文本
            ctx.setTextAlign('center'); // 文字居中对齐
            ctx.setFillStyle('#ee6c0a'); // 设置文字颜色
            ctx.fillText(text, 170, 465); // 绘制按钮文字

            // 结束绘制
            ctx.draw();
          }
        }
      });
    },

    // 保存到相册
    savePoster() {
      uni.canvasToTempFilePath({
        canvasId: this.postCanvasId,
        success: (res) => {
          uni.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: () => {
              uni.showToast({
                title: '保存成功',
                icon: 'success'
              });
            },
            fail: (err) => {
              console.error('保存失败', err);
            }
          });
        },
        fail: (err) => {
          console.error('生成海报失败', err);
        }
      });
    },

    openPoster: function () {
      this.showPoster = true;
    },

    closePoster: function () {
      var info = this.info;
      this.drawPoster(info.qr_path, info.avatar, info.username);

      this.showPoster = false;
    },
  },
}
</script>

<style lang="scss">
.app-container {
  display: flex;
  flex-direction: column;
  align-items: center;

  .info {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 20rpx;
    background: $main-background;
    width: 400rpx;
    height: 400rpx;
    border-radius: 20rpx;

    .qr {
      width: 340rpx;
      height: 340rpx;
    }
  }

  .poster-btn {
    background-color: $main-color;
    color: #fff;
    font-size: 32rpx;
    border: none;
    border-radius: 20rpx;
    margin-top: 20rpx;
    padding: 0 40rpx;
  }

  .gather-box {
    width: 85%;
    padding: 20rpx;
    background: $main-background;
    border-radius: 20rpx;
    margin-top: 40rpx;
    display: flex;
    flex-direction: column;
    align-items: center;

    .text {
      font-size: 36rpx;
    }

    .btn-box {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
      margin-top: 20rpx;
      font-size: 32rpx;

      .box {
        display: flex;
        align-items: center;

        .icon {
          width: 30rpx;
          height: 30rpx;
          margin-right: 10rpx;
        }
      }
    }
  }

  .detail-box {
    width: calc(85% - 40rpx);
    height: 560rpx;
    overflow: hidden;
    padding: 40rpx;
    border-radius: 20rpx;
    margin-top: 40rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    font-size: 32rpx;
    background: $main-background;

    .list-box {
      margin-top: 30rpx;
      max-height: 35vh;

      .box {
        display: flex;
        align-items: center;
        flex-direction: column;
        position: relative;
        margin-top: 40rpx;
        height: 180rpx;

        .user-info {
          display: flex;
          align-items: center;
          width: 100%;

          .avatar {
            width: 140rpx;
            height: 140rpx;
            border-radius: 50%;
            margin-right: 30rpx;
          }
        }

      }

      .time {
        position: absolute;
        font-size: 32rpx;
        margin-top: 10rpx;
        bottom: 0;
        right: 0;
      }
    }

  }

  .modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;

    .modal {
      position: relative;
      width: 80%;

      .close {
        position: absolute;
        width: 40rpx;
        height: 40rpx;
        border-radius: 50%;
        right: 20rpx;
        top: 40rpx;
      }

      .modal-content {
        background: #fff;
        padding: 20rpx;
        border-radius: 20rpx;
        max-height: 70vh;
        margin-top: 20rpx;

        .content {
          margin-top: 50rpx;
          height: calc(70vh - 60rpx);
        }
      }
    }
  }

  .poster-container {
    position: fixed; /* 固定位置，使弹框悬浮在页面上 */
    top: 50%; /* 垂直居中 */
    left: 50%; /* 水平居中 */
    transform: translate(-50%, -50%); /* 使弹框的中心与页面的中心对齐 */
    width: 100vw;
    height: 100vh;
    background-color: rgba(0, 0, 0, 0.6); /* 半透明背景，突出弹框内容 */
    box-sizing: border-box;
    z-index: 999; /* 保证弹框显示在最前 */
    display: flex;
    flex-direction: column;
    align-items: center;

    canvas {
      width: 100%;
      height: auto;
      border-radius: 10rpx;
      margin-top: 13vh;
    }

    .poster-btn-box {
      width: 670rpx;
      display: flex;
      justify-content: space-between;
      margin-top: 20rpx;

      .btn {
        background-color: $main-color;
        color: #fff;
        font-size: 32rpx;
        border-radius: 40rpx;
        box-shadow: 0rpx 4rpx 10rpx rgba(0, 0, 0, 0.1);
      }

      .close {
        width: 30%;
        margin-right: 10rpx;
        background-color: #A5A5A5;
      }
    }
  }


}
</style>

